#include "landload.h"
#include "../utils/log.h"

Landload_t *landload;

void landload_init() {
    landload = malloc(sizeof(Landload_t));
    landload->game_count = 0;
    INIT_LIST_HEAD(&landload->game_list.list);
    landload->map = NULL;
    return landload;
}
void landload_add_game(game_node_t *game) {
    // 添加游戏到列表
    list_add_tail(&game->list, &landload->game_list.list);
    // 更新游戏数量
    landload->game_count++;
    game_map *entry = malloc(sizeof(game_map));
    entry->node = game;
    entry->id = game->game->id;

    // 添加游戏到哈希表
    int id = game->game->id;
    HASH_ADD_INT(landload->map, id, entry);
}

void landload_remove_game(game_node_t *game) {
    // 从列表中移除游戏
    list_del(&game->list);
    // 更新游戏数量
    landload->game_count--;
}

game_t *landload_get_game(int game_id) {
    // 遍历游戏列表，查找指定游戏
    game_map *entry;
    HASH_FIND_INT(landload->map, &game_id, entry);

    if (entry != NULL) {
        return entry->node->game;
    }
    return NULL;
}

game_node_t *landload_get_game_node(int game_id) {
    // 遍历游戏列表，查找指定游戏
    game_map *entry;
    HASH_FIND_INT(landload->map, &game_id, entry);

    if (entry) {
        return entry->node;
    }
    return NULL;
}

void landload_destory() {
    // 释放内存
    game_node_t *game_node, *tmp;
    list_for_each_entry_safe(game_node, tmp, &landload->game_list.list, list) {
        list_del(&game_node->list);
        free(game_node);
        landload->game_count--;
    }
    // 释放哈希表
    game_map *entry, *t;
    HASH_ITER(hh, landload->map, entry, t) {
        HASH_DEL(landload->map, entry);
        free(entry);
    }
    free(landload);
}